// lib/services/coffee_service.dart
import 'package:dio/dio.dart';
import 'package:cesi/model/Coffee.dart'; // 导入 Coffee 模型

// 创建一个单例模式的 Dio 实例
final Dio _dio = Dio(
  BaseOptions(
    baseUrl: 'http://10.0.2.2:8080', // 你的后端基础地址
    connectTimeout: const Duration(seconds: 5), // 修复：使用 Duration
    receiveTimeout: const Duration(seconds: 3), // 修复：使用 Duration
  ),
);

class CoffeeService {
  CoffeeService._internal(); // 私有构造函数
  static final CoffeeService _instance = CoffeeService._internal();
  factory CoffeeService() => _instance; // 工厂构造函数，提供单例

  // 获取所有咖啡的方法
  Future<List<Coffee>> getAllCoffees() async {
    try {
      final Response response = await _dio.get('/coffee/list');
      if (response.statusCode == 200) {
        final serverResponse = response.data;
        if (serverResponse['code'] == '200') {
          List<dynamic> data = serverResponse['data'];
          List<Coffee> coffees = data
              .map((json) => Coffee.fromJson(json))
              .toList();
          return coffees;
        } else {
          throw Exception('获取咖啡列表失败: ${serverResponse['msg']}');
        }
      } else {
        throw Exception('请求失败，状态码: ${response.statusCode}');
      }
    } on DioException catch (e) {
      String errorMessage = '网络请求发生错误';
      if (e.type == DioExceptionType.connectionTimeout) {
        errorMessage = '连接超时，请检查网络或服务器状态。';
      } else if (e.type == DioExceptionType.connectionError) {
        errorMessage = '连接被拒绝，请确保后端服务正在运行且地址正确。';
      }
      throw Exception(errorMessage);
    } catch (e) {
      throw Exception('发生未知错误: $e');
    }
  }
}
